#!/usr/bin/env node

const fs = require('fs');
const path = require('path');
const program = require('./js/dialog').commander();

program
  .version('0.0.1')
  .option('-f, --file [n]', '最终生产的文件，如果为空，则为工程平行目录的[工程名称].md')
  .parse(process.argv);

let { file } = program;
const project = path.basename(process.cwd());
if (!file) {
  file = `../${project}.md`;
}

function readProjectFiles(rootDir, outputFile) {
  const outputStream = fs.createWriteStream(outputFile, { encoding: 'utf-8' });
  // outputStream.write('## 工程文件如下：\n');
  // outputStream.write('下面是这个工程包含的所有的文件\n\n');
  outputStream.write("=== Project Overview ===\n");
  outputStream.write("This is a project containing code files for analysis.\n\n");
  function traverseDirectory(currentDir) {
    const items = fs.readdirSync(currentDir, { withFileTypes: true });
    for (const item of items) {
      const itemPath = path.join(currentDir, item.name);
      if (item.isDirectory()) {
        if (['node_modules', 'buildApp', 'unpackage', '.hbuilderx', '.vscode'].includes(item.name)) continue;
        traverseDirectory(itemPath);
      } else if (item.isFile()) {
        if (['package-lock.json'].includes(item.name)) continue;
        try {
          const fileContent = fs.readFileSync(itemPath, 'utf-8');
          // outputStream.write(`### ${itemPath}\n`);
          outputStream.write(`=== File: ${itemPath.replaceAll('\\', '/')} ===\n`);
          // outputStream.write('```' + (path.extname(item.name || '').slice(1)) + '\n');
          outputStream.write(fileContent);
          outputStream.write("\n\n"); // 添加空行分隔
          // outputStream.write('\n```\n\n'); // 添加空行分隔
        } catch (error) {
          console.error(`Error reading ${itemPath}:`, error);
        }
      }
    }
  }
  traverseDirectory(rootDir);
  outputStream.end();
  console.log(`Project document generated at: ${outputFile}`);
}


readProjectFiles('.', file);
